package com.vic.framework.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JSON工具类
 * @author VIC
 *
 */
public final class JsonUtil {

	private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
	
	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
	static{
		OBJECT_MAPPER.setVisibilityChecker(OBJECT_MAPPER.getVisibilityChecker().withFieldVisibility(Visibility.ANY));
	}
	
	/**
	 * 对象转JSON
	 */
	public static <T> String toJson(T obj) {
		String json;
		try{
			
			json = OBJECT_MAPPER.writeValueAsString(obj);
		}catch(Exception e) {
			logger.error("convert to json failure", e);
			throw new RuntimeException(e);
		}
		return json;
	}
	
	/**
	 * JSON转对象
	 */
	public static <T> T fromJson(String json, Class<T> type){
		T t;
		try{
			t = OBJECT_MAPPER.readValue(json, type);
		}catch(Exception e) {
			logger.info("conver json to pojo failure", e);
			throw new RuntimeException(e);
		}
		return t;
	}
}
